package com.zxgj.datadirect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxgj.datadirect.entity.DataDirectOuterApply;
import com.zxgj.datadirect.mapper.DataDirectOuterApplyMapper;
import com.zxgj.datadirect.service.DataDirectOuterApplyService;
import com.zxgj.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 外来申请服务实现类
 * 
 * @author ruoyi
 */
@Slf4j
@Service
public class DataDirectOuterApplyServiceImpl extends ServiceImpl<DataDirectOuterApplyMapper, DataDirectOuterApply>
        implements DataDirectOuterApplyService {

    /**
     * 根据申请单号查询外来申请
     */
    @Override
    public DataDirectOuterApply getByApplyNo(String applyNo) {
        if (StringUtils.isEmpty(applyNo)) {
            return null;
        }
        LambdaQueryWrapper<DataDirectOuterApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDirectOuterApply::getApplyNo, applyNo);
        return this.getOne(wrapper);
    }

    /**
     * 根据目标机构编码查询待审批的外来申请
     */
    @Override
    public List<DataDirectOuterApply> getPendingByTargetOrg(String targetOrgCode) {
        if (StringUtils.isEmpty(targetOrgCode)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<DataDirectOuterApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDirectOuterApply::getTargetOrgCode, targetOrgCode);
        wrapper.eq(DataDirectOuterApply::getApproveStatus, 0); // 待审批状态
        wrapper.orderByDesc(DataDirectOuterApply::getCreateTime);
        return this.list(wrapper);
    }

    /**
     * 分页查询外来申请
     */
    @Override
    public Page<DataDirectOuterApply> getOuterApplyPage(Page<DataDirectOuterApply> page, 
                                                       String targetOrgCode, 
                                                       Integer approveStatus) {
        LambdaQueryWrapper<DataDirectOuterApply> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotEmpty(targetOrgCode)) {
            wrapper.eq(DataDirectOuterApply::getTargetOrgCode, targetOrgCode);
        }
        if (approveStatus != null) {
            wrapper.eq(DataDirectOuterApply::getApproveStatus, approveStatus);
        }
        
        wrapper.orderByDesc(DataDirectOuterApply::getCreateTime);
        return this.page(page, wrapper);
    }

    /**
     * 批量审批外来申请
     */
    @Override
    @Transactional
    public int batchApprove(List<String> applyNos, Integer approveStatus, String approveOpinion, String approveUser) {
        if (applyNos == null || applyNos.isEmpty()) {
            return 0;
        }

        int successCount = 0;
        Date now = new Date();

        for (String applyNo : applyNos) {
            try {
                DataDirectOuterApply apply = this.getByApplyNo(applyNo);
                if (apply != null && apply.getApproveStatus() == 0) { // 只有待审批的才能审批
                    apply.setApproveStatus(approveStatus);
                    apply.setApproveOpinion(approveOpinion);
                    apply.setApproveUser(approveUser);
                    apply.setApproveTime(now);
                    apply.setUpdateBy(approveUser);
                    apply.setUpdateTime(now);

                    boolean result = this.updateById(apply);
                    if (result) {
                        successCount++;
                        log.info("审批外来申请成功，申请单号: {}, 审批状态: {}", applyNo, approveStatus);
                    }
                }
            } catch (Exception e) {
                log.error("审批外来申请失败，申请单号: {}, 错误信息: {}", applyNo, e.getMessage());
                continue;
            }
        }

        return successCount;
    }

    /**
     * 标记申请已读
     */
    @Override
    public boolean markAsRead(String applyNo) {
        if (StringUtils.isEmpty(applyNo)) {
            return false;
        }

        LambdaQueryWrapper<DataDirectOuterApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDirectOuterApply::getApplyNo, applyNo);
        
        DataDirectOuterApply apply = this.getOne(wrapper);
        if (apply != null && apply.getReadStatus() == 0) {
            apply.setReadStatus(1);
            apply.setUpdateTime(new Date());
            return this.updateById(apply);
        }
        
        return false;
    }

    /**
     * 统计待审批数量
     */
    @Override
    public int countPendingByTargetOrg(String targetOrgCode) {
        if (StringUtils.isEmpty(targetOrgCode)) {
            return 0;
        }
        
        LambdaQueryWrapper<DataDirectOuterApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDirectOuterApply::getTargetOrgCode, targetOrgCode);
        wrapper.eq(DataDirectOuterApply::getApproveStatus, 0); // 待审批状态
        
        return (int) this.count(wrapper);
    }

    /**
     * 同步国家平台外来申请数据
     */
    @Override
    @Transactional
    public int syncFromNationalPlatform() {
        log.info("开始同步国家平台外来申请数据");
        
        // 这里应该调用国家平台API获取外来申请数据
        // 由于是模拟实现，这里只是记录日志
        int syncCount = 0;
        
        try {
            // 模拟同步逻辑
            // 1. 调用国家平台API获取外来申请列表
            // 2. 对比本地数据，新增或更新记录
            // 3. 生成待办任务
            
            log.info("同步国家平台外来申请数据完成，同步数量: {}", syncCount);
        } catch (Exception e) {
            log.error("同步国家平台外来申请数据失败: {}", e.getMessage());
        }
        
        return syncCount;
    }
}
